package com.spring.security.filter;

import com.spring.security.utils.Contants;
import com.spring.security.utils.TokenInfo;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.annotation.Order;
import org.springframework.http.*;
import org.springframework.stereotype.Component;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.util.StringUtils;
import org.springframework.web.client.RestTemplate;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.util.HashSet;
import java.util.Set;

/**
 * 认证过滤器
 */
@Component
@Order(1)
public class AuthenticationFilter implements GlobalFilter, InitializingBean {

    private Set<String> skipUrls = new HashSet<>();

    @Autowired
    @Qualifier("restTemplate")
    private RestTemplate restTemplate;

    @Override
    public void afterPropertiesSet() throws Exception {
        skipUrls.add("/oauth/token");
        skipUrls.add("/oauth/check_token");
        skipUrls.add("/user/getUser");
        skipUrls.add("/auth/getAuth");
    }

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {

        String requestPath = exchange.getRequest().getURI().getPath();
        if (isSkip(requestPath)) {
            return chain.filter(exchange);
        }

        String authHeader = exchange.getRequest().getHeaders().getFirst("Authorization");

        if (StringUtils.isEmpty(authHeader)) {
            throw new RuntimeException("请求头为空");
        }
        TokenInfo info = null;
        try {
            info = getTokenInfo(authHeader);
        } catch (Exception ce) {
            ce.printStackTrace();
            throw new RuntimeException("校验令牌异常");
        }
        exchange.getAttributes().put("tokenInfo", info);
        return chain.filter(exchange);
    }

    /**
     * 校验token，校验成功返回一个token信息
     *
     * @return
     */
    private TokenInfo getTokenInfo(String authHeader) {
        String token = org.apache.commons.lang3.StringUtils.substringAfter(authHeader, "bearer ");
        if (StringUtils.isEmpty(token)) {
            throw new RuntimeException("token为空");
        }
        HttpHeaders httpHeaders = new HttpHeaders();
        httpHeaders.setContentType(MediaType.APPLICATION_FORM_URLENCODED);
        httpHeaders.setBasicAuth(Contants.clientId, Contants.clientSecret);
        MultiValueMap<String, String> multiValueMap = new LinkedMultiValueMap<>();
        multiValueMap.add("token", token);
        HttpEntity<MultiValueMap<String, String>> entity = new HttpEntity<>(multiValueMap,httpHeaders);
        //检验成功，返回一个token信息
        ResponseEntity<TokenInfo> exchange = restTemplate.exchange(Contants.checkTokenUrl, HttpMethod.POST, entity, TokenInfo.class);
        return exchange.getBody();
    }

    private boolean isSkip(String requestPath) {
        for (String skipUrl : skipUrls) {
            if (requestPath.contains(skipUrl)) {
                return true;
            }
        }
        return false;
    }
}
